package com.swas.service.impl;

import com.swas.dao.PermDao;
import com.swas.entity.Perm;
import com.swas.entity.PermExample;
import com.swas.service.PermService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lxysky
 */
@Transactional
@Service
public class PermServiceImpl implements PermService {

    @Autowired
    private PermDao permDao;

    @Override
    public List<Perm> selectPermAll() {
        PermExample example = new PermExample();
        example.createCriteria().andParentidEqualTo(0);
        List<Perm> rootList = permDao.selectByExample(example);
        List<Perm> baseList = permDao.selectByExample(null);
        tree(rootList, baseList);
        return rootList;
    }

    private void tree(List<Perm> rootList, List<Perm> baseList) {
        for (Perm root : rootList){
            List<Perm> children = new ArrayList<>();
            for (Perm child : baseList){
                if(child.getParentid().equals(root.getId())){
                    children.add(child);
                }
            }
            if(children.size()>0){
                tree(children,baseList);
            }
            root.setChildren(children);
        }
    }
}
